/*//在node环境中，当遇到require(x),从[安装在package.json的模块] 或 [node内置的模块] 中返回该模块
//依次在每个目录中当成文件名或者目录加载
let http = require('http')//当x不带路径时根据所在的父模块，确定x可能的安装目录
let mysql = require('mysql');
const {param} = require("express/lib/router");
const QueryString = require("querystring");
const server = http.createServer(function (req, res) {
    res.statusCode = 200
    res.setHeader("Access-Control-Allow-Origin", "*");//设置响应头跨域
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.setHeader("X-Powered-By", ' 3.2.1')
    res.setHeader("Content-Type", "application/json;charset=utf-8");
    res.setHeader('Content-Type', 'text/plain;charset=utf-8')
})
// 创建一个数据库连接池
let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'library'
});
connection.connect(function (err) {
    if (err) {
        console.log('error')
    }
    console.log('connect success!')
});//连接
server.on('request', function (request,response,) {
    let url = request.url
    if (url === '/') {
        // 查询数据
        connection.query('select * from book', function (err, row) {
            if (err) {
                console.log(err)
            }
            let data = JSON.stringify(row)
            response.end(data)
        })
    }
    // 查询数据
     if (url === '/post') {
        connection.query('UPDATE book SET name = ?, publishhouse = ? , amount=? ,borrowstate = ?, classify=? WHERE bid = ?',[2,'B0001'], function (err, row) {
            if (err) {
                console.log(err)
            }
            /!*let data = JSON.stringify(row)*!/
            response.end()
        })
    }
});
server.listen(3000, () => {
    console.log('服务器开启成功！')
})*/

let express = require('express')
let app = express()
let mysql = require('mysql');
let bodyParser = require('body-parser');
//只要加入这个配置，在req请求对象上会多出来一个属性
app.use(bodyParser.urlencoded({extended: false}))
//parse application/json
app.use(bodyParser.json())

// 创建一个数据库连接池
let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'library'
});
connection.connect(function (err) {
    if (err) {
        console.log('error')
    }
    console.log('database connect success!')
});//连接


//--------------------------------------------------bookManage----------------------------------------------------------
app.get('/bookManage/get', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    connection.query('select * from book', function (err, row) {
        if (err) {
            console.log(err)
        }
        let data = JSON.stringify(row)
        res.end(data)
    })
});
//post请求
app.post('/bookManage/amend', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    /*    console.log('收到post请求了')*/
    //获取url中的请求参数
    let query = req.query
    connection.query('UPDATE book SET name = ?, publishhouse = ? , amount=? ,borrowstate = ?, classify=? WHERE bid = ?',
        [query.name, query.publishhouse, query.amount, query.borrowstate, query.classify, query.bid], function (err, row) {
            if (err) {
                console.log(err)
            }
            res.end()
        })
    //在Express中没有内置获取表单post请求的api，
    //这里我们需要使用一个第三方包 body-parser
    /* let params = req.params*/
    /* console.log(req.body)*/
    /*res.end(JSON.stringify(query))*/
});
app.post('/bookManage/insert', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //获取url中的请求参数
    let query = req.query
    connection.query('INSERT INTO book VALUES (?,?,?,?,?,?)',
        [query.bid, query.name, query.publishhouse, query.amount, query.borrowstate, query.classify,], function (err, row) {
            if (err) {
                console.log(err)
            }
            res.end("success!")
        })
});

app.post('/bookManage/delete', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //获取url中的请求参数
    let query = req.query
    connection.query( 'DELETE FROM book WHERE bid = ?', [query.bid], function (err, row) {
        if (err) {
            console.log(err)
        }
        res.end("success!")
    })
});
//--------------------------------------------------bookManage----------------------------------------------------------


//------------------------------------------------magazineManage--------------------------------------------------------
app.get('/magazineManage/get', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    connection.query('select * from magazine', function (err, row) {
        if (err) {
            console.log(err)
        }
        let data = JSON.stringify(row)
        res.end(data)
    })
});
//post请求
app.post('/magazineManage/amend', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    /*    console.log('收到post请求了')*/
    //获取url中的请求参数
    let query = req.query
    connection.query('UPDATE magazine SET name = ?, publishDate = ? , amount=? ,borrowstate = ?, classify=? WHERE mid = ?',
        [query.name, query.publishDate, query.amount, query.borrowstate, query.classify, query.mid], function (err, row) {
            if (err) {
                console.log(err)
            }
            res.end()
        })
});
app.post('/magazineManage/insert', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //获取url中的请求参数
    let query = req.query
    connection.query('INSERT INTO magazine VALUES (?,?,?,?,?,?)',
        [query.mid, query.name, query.publishDate, query.amount, query.borrowstate, query.classify,], function (err, row) {
            if (err) {
                console.log(err)
            }
            res.end("success!")
        })
});

app.post('/magazineManage/delete', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //获取url中的请求参数
    let query = req.query
    connection.query( 'DELETE FROM magazine WHERE mid = ?', [query.mid], function (err, row) {
        if (err) {
            console.log(err)
        }
        res.end("success!")
    })
});
// ------------------------------------------------magazineManage--------------------------------------------------------


// ------------------------------------------------borrowManage--------------------------------------------------------
app.get('/borrowManage/get', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    connection.query('select * from borrow', function (err, row) {
        if (err) {
            console.log(err)
        }
        let data = JSON.stringify(row)
        res.end(data)
    })
});
//post请求
app.post('/borrowManage/amend', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    /*    console.log('收到post请求了')*/
    //获取url中的请求参数
    let query = req.query
    connection.query('UPDATE borrow SET borrowBook = ?, borrowDate = ? , borrowAmount=? ,borrowdebt = ?WHERE uid = ?',
        [query.borrowBook, query.borrowDate, query.borrowAmount, query.borrowdebt,query.uid], function (err, row) {
            if (err) {
                console.log(err)
            }
            res.end()
        })
});
app.post('/borrowManage/insert', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //获取url中的请求参数
    let query = req.query
    connection.query('INSERT INTO borrow VALUES (?,?,?,?,?)',
        [query.uid, query.borrowBook, query.borrowDate, query.borrowAmount, query.borrowdebt], function (err, row) {
            if (err) {
                console.log(err)
            }
            res.end("success!")
        })
});

app.post('/borrowManage/delete', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //获取url中的请求参数
    let query = req.query
    connection.query( 'DELETE FROM borrow WHERE uid = ?', [query.uid], function (err, row) {
        if (err) {
            console.log(err)
        }
        res.end("success!")
    })
});
// ------------------------------------------------borrowManage--------------------------------------------------------

// -------------------------------------------------staffManage---------------------------------------------------------
app.get('/staffManage/get', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    connection.query('select * from staff', function (err, row) {
        if (err) {
            console.log(err)
        }
        let data = JSON.stringify(row)
        res.end(data)
    })
});
//post请求
app.post('/staffManage/amend', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    /*    console.log('收到post请求了')*/
    //获取url中的请求参数
    let query = req.query
    connection.query('UPDATE staff SET staffname = ?, entryDate = ? , department=? ,job = ?WHERE sid = ?',
        [query.staffname, query.entryDate, query.department, query.job,query.sid], function (err, row) {
            if (err) {
                console.log(err)
            }
            res.end()
        })
});
app.post('/staffManage/insert', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //获取url中的请求参数
    let query = req.query
    connection.query('INSERT INTO staff VALUES (?,?,?,?,?)',
        [query.sid, query.staffname, query.entryDate, query.department, query.job], function (err, row) {
            if (err) {
                console.log(err)
            }
            res.end("success!")
        })
});

app.post('/staffManage/delete', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //获取url中的请求参数
    let query = req.query
    connection.query( 'DELETE FROM staff WHERE sid = ?', [query.sid], function (err, row) {
        if (err) {
            console.log(err)
        }
        res.end("success!")
    })
});
// -------------------------------------------------staffManage---------------------------------------------------------

// ----------------------------------------------------login------------------------------------------------------------
app.post('/login/username', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //获取url中的请求参数
    let query = req.query;
    let notExist=true;
   connection.query( 'SELECT username FROM admin',function (err, row) {
        if (err) {
            res.end("error")
        }
        for (let i=0;i<row.length;i++){
            if (row[i].username===query.username){
                i=row.length;
                res.end("success");
            }else if((i+1)===row.length){
                res.end("error")
            }
        }
        res.end();
    })
});
app.post('/login/password', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //获取url中的请求参数
    let query = req.query
    connection.query( 'SELECT password FROM admin WHERE username=?', [query.username], function (err, row) {
        if (err) {
            res.end("error")
        }
        if(row[0].password === query.password){
            res.end("success")
        }else{
            res.end("error")
        }
    })
});
// ----------------------------------------------------login------------------------------------------------------------

app.listen(3000, function () {
    console.log('start')
})